
// Node.js require:
const Ajv = require("ajv").default
const addFormats = require("ajv-formats")
var localize = require('ajv-i18n');

const schema = {
  type: 'object',
  properties: {
    name: {
      type: 'string',
      format: 'email',
      key: true,
      key2: true,
      key3: true,
      errorMessage: {
        type: '必须是字符串',
        minLength: '长度不能小于10'
      }
    },
    nick: {
      type: 'string',
      format: 'test',
      minLength:10,
      errorMessage: {
        type: '必须是字符串',
        minLength: '长度不能小于10'
      }
    },
    age: {
      type: 'number'
    },
    pets: {
      type: 'array',
      items: {
        type: 'string'
      }
    },
    isWorker: {
      type: 'boolean'
    }
  },
  required:['name','age']
}

const ajv = new Ajv({allErrors: true}) // options can be passed, e.g. {allErrors: true}
require("ajv-errors")(ajv /*, {singleError: true} */)
addFormats(ajv)

// 自定义format
ajv.addFormat('test', (data) => {
  console.log(data, '----')
  return data === 'aqie'
})

// 自定义关键字1
ajv.addKeyword('key', {
  validate: function fun(schema, data) {
    fun.errors = [{
      dataPath: "/name",
      keyword: "key",
      message: "good night",
      params: {},
      schemaPath: "#/properties/name/key"
    }]

    console.log(schema, data)
    if(schema === true){
      return true
    } else {
      return schema.length === 6
    }
  }
})
// 自定义关键字 2
ajv.addKeyword('key2', {
  compile(schema, parentSchema) {
    console.log('key2',schema, parentSchema)
    return () => true
  },
  metaSchema: {
    type: 'boolean'   // key2 值 必须是string  false
  }
})

ajv.addKeyword('key3', {
  macro() {
    return {
      minLength: 10,
    }
  }
})

// todo inline

const validate = ajv.compile(schema)
const valid = validate({
  name:'aqie@qq.com',
  age:18,
  nick: 'aqie',
  pets:['pig','dog'],
  isWorker: true
})

if (!valid){
  localize.zh(validate.errors);
  console.log(validate.errors)
} 